package btree;

import index.IndexException;
import index.IndexScan;
import iterator.BPHeapfile;
import iterator.BPIterator;
import iterator.CondExpr;
import iterator.DuplElim;
import iterator.DuplElimException;
import iterator.FileScan;
import iterator.FileScanException;
import iterator.FldSpec;
import iterator.InvalidRelation;
import iterator.Iterator;
import iterator.JoinsException;
import iterator.LowMemException;
import iterator.NestedLoopsJoins;
import iterator.PredEvalException;
import iterator.RelSpec;
import iterator.Sort;
import iterator.SortException;
import iterator.TupleUtilsException;
import iterator.UnknowAttrType;
import iterator.UnknownKeyTypeException;
import iterator.WrongPermat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;

import tests.Log;
import tests.runTest;

import code.FileStatistics;
import code.PCounter;
import code.SortUtility;
import diskmgr.rdfDB;

import btree.BTreeFile;
import btree.StringKey;
import bufmgr.PageNotReadException;

import global.AttrOperator;
import global.AttrType;
import global.EID;
import global.IndexType;
import global.PID;
import global.PageId;
import global.RID;
import global.SystemDefs;
import global.TID;
import global.TupleOrder;
import heap.BasicPattern;
import heap.FieldNumberOutOfBoundException;
import heap.FileAlreadyDeletedException;
import heap.HFBufMgrException;
import heap.HFDiskMgrException;
import heap.HFException;
import heap.Heapfile;
import heap.InvalidSlotNumberException;
import heap.InvalidTupleSizeException;
import heap.InvalidTypeException;
import heap.LabelHeapfile;
import heap.Scan;
import heap.SpaceNotAvailableException;
import heap.StringLabel;
import heap.TemporaryTriple;
import heap.Triple;
import heap.TripleHeapfile;
import heap.Tuple;

public class Interface3 {
	
	private static Log log = Log.getInstance(Interface3.class.getName());

	public   LabelHeapfile entityHeap;
	public   LabelHeapfile predicateHeap;
	public   TripleHeapfile tripleHeap;
	public   Heapfile temporaryHeap;
	public   Heapfile [] THFHeap;
	public   SystemDefs sysdef;
	public  static short TEMPORARY_TRIPLE_SIZE;
	private  String dbName = null;
	private  static int NUMBUF = 100;
	public static boolean DEBUG = true;
	public SortUtility sutil;
	public int counter = 0;
	public AttrType [] BPtypes = {};
	private int level = 1;
	private int lastBPLength;
	private boolean secondJoinFirstRun = true;
	private NestedLoopsJoins JnOp2 = null;
	private AttrType[] bp_attrtypes_print = null;
	private int count_record=0;
	public float bp_conf_filter=(float) 0.0;
	//public float rht_conf_filter_1=(float) 0.0;
	//public float rht_conf_filter_2=(float) 0.0;
	public static int cheatingCounter = 0;
	
	public FileStatistics stats = null;

	/*   {
		try {
			init("/tmp/dbtest", 1000);
		} catch (InvalidTypeException e) {
			e.printStackTrace();
		} catch (InvalidTupleSizeException e) {
			e.printStackTrace();
		} catch (FieldNumberOutOfBoundException e) {
			e.printStackTrace();
		}
	} */

	public FileStatistics getStats() {
		return stats;
	}

	public void superinit(String db, int Numbuf, int counter) throws InvalidTypeException,
	InvalidTupleSizeException, FieldNumberOutOfBoundException {
		try {
			NUMBUF = Numbuf;
			dbName = db;
			this.counter = counter;
			int NUMPAGES = 30000;
			sysdef = new SystemDefs(dbName, NUMPAGES, NUMBUF, "Clock");
		} catch (Exception e){
			e.printStackTrace();
		}
	}
	
	public   void init(String db, int Numbuf, int counter) throws InvalidTypeException,
			InvalidTupleSizeException, FieldNumberOutOfBoundException {

		try {
			this.counter = counter;
			TEMPORARY_TRIPLE_SIZE = 203;
			stats = new FileStatistics();
			System.out.println("Creating heap files");
			entityHeap = new LabelHeapfile("entities"+counter);
			predicateHeap = new LabelHeapfile("predicates"+counter);
			tripleHeap = new TripleHeapfile("triples"+counter);
			
			createIndex(tripleHeap, RdbIndexType.SPO);
			createIndex(tripleHeap, RdbIndexType.PSO);
			createIndex(tripleHeap, RdbIndexType.SC);
			createIndex(tripleHeap, RdbIndexType.PC);
			createIndex(tripleHeap, RdbIndexType.OC);
			createIndex(tripleHeap, RdbIndexType.C);
			createIndex(tripleHeap, RdbIndexType.SO);
			createIndex(tripleHeap, RdbIndexType.PO);
			createIndex(entityHeap, RdbIndexType.E);
			createIndex(predicateHeap, RdbIndexType.P);

			
			
		} catch (HFException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HFBufMgrException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HFDiskMgrException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public   String getSubjectRID(String subject, RID rid)
			throws Exception {
		return getLabelRID("entities" + counter, subject, "BTreeIndex_" + RdbIndexType.E + counter,
				rid);
	}

	/*
	 * OBSOLETE CODE
	 * if only I has listened to Smriti :(
	public Tuple JoinSecondLevelQuery(String subjectFilterLFT,String predicateFilterLFT, String objectFilterLFT, Float confidenceLFT,
			String subjectFilterRHT1,String predicateFilterRHT1, String objectFilterRHT1, Float confidenceRHT1,
			RdbIndexType orderOption, int buf_size,
			int JoinNodePosition1 , int JoinOnSubOb1 ,int OutputRightSubject1, 
			int OutputRightObject1,
			String subjectFilterRHT2,String predicateFilterRHT2, String objectFilterRHT2,Float confidenceRHT2,
			int JoinNodePosition2,int JoinOnSubOb2,int OutputRightSubject2, 
			int OutputRightObject2, int[] LONP1, int[] LONP2 )
			throws JoinsException, IndexException, 
			InvalidTupleSizeException, InvalidTypeException, PageNotReadException, 
			TupleUtilsException, PredEvalException, SortException, 
			LowMemException, UnknowAttrType, UnknownKeyTypeException, IOException, Exception{
		
		if (secondJoinFirstRun) {
			secondJoinFirstRun = false;
			Iterator itr=querySystemForJoin(subjectFilterLFT, predicateFilterLFT, objectFilterLFT, confidenceLFT, orderOption, buf_size);
			NestedLoopsJoins JnOp=null;
			
			AttrType[] bptypes = {
					new AttrType(AttrType.attrInteger), 
					new AttrType(AttrType.attrInteger), 
					new AttrType(AttrType.attrInteger),
					new AttrType(AttrType.attrInteger),
					new AttrType(AttrType.attrInteger),
					new AttrType(AttrType.attrInteger),
					new AttrType(AttrType.attrReal) 
			}; 
			this.BPtypes = bptypes;
			System.out.println("BPTypes for the first pass: "+BPtypes.length);
			lastBPLength = BPtypes.length;
			level = 1;
			JnOp=JoinQuery( itr,
					subjectFilterRHT1, predicateFilterRHT1, objectFilterRHT1, confidenceRHT1,
					orderOption,  buf_size,
					JoinNodePosition1 ,  JoinOnSubOb1 , OutputRightSubject1, OutputRightObject1, LONP1);

			this.BPtypes=Query_proj_attr( LONP1,OutputRightSubject1,OutputRightObject1);
			System.out.println("BPTypes for the second pass: "+BPtypes.length);
			level = 2;
			lastBPLength = BPtypes.length;
			THFHeap.deleteFile();
			THFHeap = new Heapfile("THFHeap");
			JnOp2=JoinQuery( JnOp,
					subjectFilterRHT2, predicateFilterRHT2, objectFilterRHT2, confidenceRHT2,
					orderOption,  buf_size,
					JoinNodePosition2 ,  JoinOnSubOb2 , OutputRightSubject2, OutputRightObject2, LONP2);
			Tuple t = null; 
			System.out.println("Results");
			bp_attrtypes_print = Query_proj_attr( LONP2,OutputRightSubject2,OutputRightObject2);
			
		}
		Tuple t = null;
		while ((t = JnOp2.get_next()) != null){
			float min_conf=(float) 0.0;
			if( t.getFloFld(bp_attrtypes_print.length-2)
					<t.getFloFld(bp_attrtypes_print.length-1)){
				min_conf= t.getFloFld(bp_attrtypes_print.length-2);
			}
			else min_conf=t.getFloFld(bp_attrtypes_print.length-1);
			if(min_conf >t.getFloFld(bp_attrtypes_print.length))
				min_conf=t.getFloFld(bp_attrtypes_print.length);
			t.setFloFld(bp_attrtypes_print.length-2, min_conf);
			t.setFloFld(bp_attrtypes_print.length-1, (float)1.0);
			t.setFloFld(bp_attrtypes_print.length, (float)1.0);

			//t.printStat();
			//t.dropLastColumn();
			//t.printStat();
			//t.dropLastColumn();
			//t.printStat();

			//t.get
			//t.print(bp_attrtypes_print);
			t.print(bp_attrtypes_print, 2);
			count_record++;
			return t;
		}
		System.out.println("Number of records matched = "+count_record);
		return null;
	}
	*/
	
	public NestedLoopsJoins JoinSecondLevelQuery(String subjectFilterLFT,String predicateFilterLFT, String objectFilterLFT, Float confidenceLFT,
			String subjectFilterRHT1,String predicateFilterRHT1, String objectFilterRHT1, Float confidenceRHT1,
			RdbIndexType orderOption, int buf_size,
			int JoinNodePosition1 , int JoinOnSubOb1 ,int OutputRightSubject1, 
			int OutputRightObject1,
			String subjectFilterRHT2,String predicateFilterRHT2, String objectFilterRHT2,Float confidenceRHT2,
			int JoinNodePosition2,int JoinOnSubOb2,int OutputRightSubject2, 
			int OutputRightObject2, int[] LONP1, int[] LONP2 )
					throws JoinsException, IndexException, 
					InvalidTupleSizeException, InvalidTypeException, PageNotReadException, 
					TupleUtilsException, PredEvalException, SortException, 
					LowMemException, UnknowAttrType, UnknownKeyTypeException, IOException, Exception{
		System.out.println("Confidence LFT :" + confidenceLFT);
		bp_conf_filter=(confidenceLFT == null)?(float)0.0:confidenceLFT;
		//rht_conf_filter_1=(confidenceRHT1 == null)?(float)0.0:confidenceRHT1;
		//rht_conf_filter_2=(confidenceRHT2 == null)?(float)0.0:confidenceRHT2;
		confidenceLFT = bp_conf_filter;
		confidenceRHT1=(confidenceRHT1==null)?(float)0.0:confidenceRHT1;
		confidenceRHT2=(confidenceRHT2==null)?(float)0.0:confidenceRHT2;
		System.out.println("bp_conf_filter :" + bp_conf_filter);
		THFHeap = new Heapfile [2];
		Iterator itr=querySystemForJoin(subjectFilterLFT, predicateFilterLFT, objectFilterLFT, confidenceLFT, orderOption, buf_size);
		NestedLoopsJoins JnOp=null;
		AttrType[] bptypes = {
				new AttrType(AttrType.attrInteger), 
				new AttrType(AttrType.attrInteger), 
				new AttrType(AttrType.attrInteger),
				new AttrType(AttrType.attrInteger),
				new AttrType(AttrType.attrInteger),
				new AttrType(AttrType.attrInteger),
				new AttrType(AttrType.attrReal) 
		}; 
		this.BPtypes = bptypes;
		System.out.println("BPTypes for the first pass: "+BPtypes.length);
		lastBPLength = BPtypes.length;
		level = 1;
		JnOp=JoinQuery( itr,
				subjectFilterRHT1, predicateFilterRHT1, objectFilterRHT1, confidenceRHT1,
				orderOption,  buf_size,
				JoinNodePosition1 ,  JoinOnSubOb1 , OutputRightSubject1, OutputRightObject1, LONP1);

		this.BPtypes=Query_proj_attr( LONP1,OutputRightSubject1,OutputRightObject1);
		System.out.println("BPTypes for the second pass: "+BPtypes.length);
		level = 2;
		lastBPLength = BPtypes.length;
		//THFHeap.deleteFile();
		//THFHeap = new Heapfile("THFHeap");
		JnOp2=JoinQuery( JnOp,
				subjectFilterRHT2, predicateFilterRHT2, objectFilterRHT2, confidenceRHT2,
				orderOption,  buf_size,
				JoinNodePosition2 ,  JoinOnSubOb2 , OutputRightSubject2, OutputRightObject2, LONP2);
		bp_attrtypes_print = Query_proj_attr( LONP2,OutputRightSubject2,OutputRightObject2);		
		return JnOp2;
	}
	
		
	public Tuple getNext () throws JoinsException, IndexException, InvalidTupleSizeException, InvalidTypeException, PageNotReadException, TupleUtilsException, PredEvalException, SortException, LowMemException, UnknowAttrType, UnknownKeyTypeException, FieldNumberOutOfBoundException, IOException, Exception {
		Tuple t = null; 
		//System.out.println("Results");
		int count_record=0;
		//System.out.println("attr length :"+bp_attrtypes_print.length);
		while ((t = JnOp2.get_next()) != null){
			float min_conf=(float) 0.0;
			if( t.getFloFld(bp_attrtypes_print.length-2)
					<t.getFloFld(bp_attrtypes_print.length-1)){
				min_conf= t.getFloFld(bp_attrtypes_print.length-2);
			}
			else min_conf=t.getFloFld(bp_attrtypes_print.length-1);
			if(min_conf >t.getFloFld(bp_attrtypes_print.length))
				min_conf=t.getFloFld(bp_attrtypes_print.length);
			t.setFloFld(bp_attrtypes_print.length-2, min_conf);
			t.setFloFld(bp_attrtypes_print.length-1, (float)1.0);
			t.setFloFld(bp_attrtypes_print.length, (float)1.0);

			//t.printStat();
			//t.dropLastColumn();
			//t.printStat();
			//t.dropLastColumn();
			//t.printStat();

			//t.get
			//t.print(bp_attrtypes_print);
			t.print(bp_attrtypes_print, 2);
			count_record++;
			return t;
		}
		System.out.println("Number of records matched = "+count_record);
		
		for (int i = 0; i < cheatingCounter;i++)
			THFHeap[i].deleteFile();
		cheatingCounter = 0;
		return null;
	}
			
	/*
	public void JoinSecondLevelQuery(String subjectFilterLFT,String predicateFilterLFT, String objectFilterLFT, Float confidenceLFT,
			String subjectFilterRHT1,String predicateFilterRHT1, String objectFilterRHT1, Float confidenceRHT1,
			RdbIndexType orderOption, int buf_size,
			int JoinNodePosition1 , int JoinOnSubOb1 ,int OutputRightSubject1, 
			int OutputRightObject1,
			String subjectFilterRHT2,String predicateFilterRHT2, String objectFilterRHT2,Float confidenceRHT2,
			int JoinNodePosition2,int JoinOnSubOb2,int OutputRightSubject2, 
			int OutputRightObject2, int[] LONP1, int[] LONP2 )
			throws JoinsException, IndexException, 
			InvalidTupleSizeException, InvalidTypeException, PageNotReadException, 
			TupleUtilsException, PredEvalException, SortException, 
			LowMemException, UnknowAttrType, UnknownKeyTypeException, IOException, Exception{
		
		Iterator itr=querySystemForJoin(subjectFilterLFT, predicateFilterLFT, objectFilterLFT, confidenceLFT, orderOption, buf_size);
		NestedLoopsJoins JnOp=null;
		NestedLoopsJoins JnOp2=null;
		 AttrType[] bptypes = {
			      new AttrType(AttrType.attrInteger), 
			      new AttrType(AttrType.attrInteger), 
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrReal) 
			    }; 
		this.BPtypes = bptypes;
		System.out.println("BPTypes for the first pass: "+BPtypes.length);
		lastBPLength = BPtypes.length;
		level = 1;
		JnOp=JoinQuery( itr,
				subjectFilterRHT1, predicateFilterRHT1, objectFilterRHT1, confidenceRHT1,
				orderOption,  buf_size,
				 JoinNodePosition1 ,  JoinOnSubOb1 , OutputRightSubject1, OutputRightObject1, LONP1);
		
		this.BPtypes=Query_proj_attr( LONP1,OutputRightSubject1,OutputRightObject1);
		System.out.println("BPTypes for the second pass: "+BPtypes.length);
		level = 2;
		lastBPLength = BPtypes.length;
		THFHeap.deleteFile();
		THFHeap = new Heapfile("THFHeap");
		JnOp2=JoinQuery( JnOp,
				subjectFilterRHT2, predicateFilterRHT2, objectFilterRHT2, confidenceRHT2,
				orderOption,  buf_size,
				 JoinNodePosition2 ,  JoinOnSubOb2 , OutputRightSubject2, OutputRightObject2, LONP2);
		Tuple t = null; 
		 System.out.println("Results");
		 AttrType[] bp_attrtypes_print = Query_proj_attr( LONP2,OutputRightSubject2,OutputRightObject2);
		 int count_record=0;
		  while ((t = JnOp2.get_next()) != null){
			  float min_conf=(float) 0.0;
			 if( t.getFloFld(bp_attrtypes_print.length-2)
					 <t.getFloFld(bp_attrtypes_print.length-1)){
				min_conf= t.getFloFld(bp_attrtypes_print.length-2);
			 }
			 else min_conf=t.getFloFld(bp_attrtypes_print.length-1);
			 if(min_conf >t.getFloFld(bp_attrtypes_print.length))
				 min_conf=t.getFloFld(bp_attrtypes_print.length);
			  t.setFloFld(bp_attrtypes_print.length-2, min_conf);
			  t.setFloFld(bp_attrtypes_print.length-1, (float)1.0);
			  t.setFloFld(bp_attrtypes_print.length, (float)1.0);
			  
			  //t.printStat();
			  //t.dropLastColumn();
			  //t.printStat();
			  //t.dropLastColumn();
			  //t.printStat();
			  
			  //t.get
			  //t.print(bp_attrtypes_print);
			 t.print(bp_attrtypes_print, 2);
			 count_record++;
		 }
		 System.out.println("Number of records matched = "+count_record);
	}
	*/
	
	public NestedLoopsJoins JoinQuery(Iterator itr,
			String subjectFilterRHT1,String predicateFilterRHT1, String objectFilterRHT1, Float confidenceRHT,
			RdbIndexType orderOption, int buf_size,
			int JoinNodePosition , int JoinOnSubOb ,int OutputRightSubject, int OutputRightObject, int[] LONP) throws JoinsException, IndexException, InvalidTupleSizeException, InvalidTypeException, PageNotReadException, TupleUtilsException, PredEvalException, SortException, LowMemException, UnknowAttrType, UnknownKeyTypeException, IOException, Exception{
		
		querySystemForJoinTHF(subjectFilterRHT1, predicateFilterRHT1, objectFilterRHT1, confidenceRHT, orderOption, buf_size);
		
	    System.out.println("calling BP Iterator") ;
	    NestedLoopsJoins JnOp=BPTripleHeapJoin(10,BPtypes.length,itr,
				 JoinNodePosition, JoinOnSubOb,  
				  confidenceRHT,
					LONP, OutputRightSubject, OutputRightObject); 
		return JnOp;
	}
	
	
	
	public NestedLoopsJoins BPTripleHeapJoin(int amt_of_mem,int num_left_nodes,
			Iterator left_itr,
			int BPjoinNodePosition, int JoinOnSubjectorObject,
			Float RightConfidenceFilterRHT,
			int[] LeftOutNodePositions, int OutputRightSubject, int OutputRightObject){
		boolean blindInsert = false;
		RID sRID = null, pRID = null, oRID = null;
		RID seid = null, pid = null, oeid = null;
		Triple triple;
		RID rid;
		Tuple tuple;
		System.out.println("Inside BP Triple Heap Join");
		   AttrType [] Trtypes = {
				      new AttrType(AttrType.attrInteger), 
				      new AttrType(AttrType.attrInteger), 
				      new AttrType(AttrType.attrInteger), 
				      new AttrType(AttrType.attrInteger),
				      new AttrType(AttrType.attrInteger),
				      new AttrType(AttrType.attrInteger),
				      new AttrType(AttrType.attrReal)
				    };

				    short []   Trsizes = null;
				    short  []  BPsizes = null ;

				    
				    CondExpr [] outFilter  = new CondExpr[3];
				    outFilter[0] = new CondExpr();
				    outFilter[1] = new CondExpr();
				    outFilter[2] = new CondExpr();

				    CondExpr [] outFilter2 = new CondExpr[3];
				    outFilter2[0] = new CondExpr();
				    outFilter2[1] = new CondExpr();
				    outFilter2[2] = new CondExpr();

				    Query2_CondExpr(outFilter, outFilter2,JoinOnSubjectorObject,BPjoinNodePosition,RightConfidenceFilterRHT);
				    FldSpec [] proj1 = null;
				    	proj1 = Query_projection( LeftOutNodePositions, OutputRightSubject, OutputRightObject);
				
				    
//				    int len = projTemp.length + 1;
//				    FldSpec []  proj1 = new FldSpec[len];
//				    int i =0;
//				    for (; i < len-1; i++) {
//				    	System.out.println("proj reads.. : "+projTemp[i].relation.key + " when i="+i);
//						proj1[i] = projTemp[i];
//					}
//				    proj1[i] = new FldSpec(new RelSpec(RelSpec.innerRel), 7);
				    
		NestedLoopsJoins inl = null;
	      try {
		inl = new NestedLoopsJoins (
					    BPtypes, num_left_nodes, BPsizes,
					    Trtypes, 7, Trsizes,
					    10,//amount of buffer pages
					    left_itr, // iterator
					    "THFHeap"+cheatingCounter, 
					    outFilter, outFilter2, proj1, proj1.length, this, BPjoinNodePosition, JoinOnSubjectorObject,
					    this,bp_conf_filter);
	      }catch(Exception e){
	    	  e.printStackTrace();
	      }
		  bp_conf_filter = 0;
		  cheatingCounter++;
		//Iterator bp_inp_iterator= new Iterator();
		
		return inl;
	}
	
	public AttrType[] Query_proj_attr(int[] LeftOutNodePositions, int OutputRightSubject, int OutputRightObject){
		ArrayList<AttrType> bpattrList = new ArrayList<AttrType>();
		int len = LeftOutNodePositions.length;
		for(int i=1; i<=len*2 ; i++){
			bpattrList.add(new AttrType(AttrType.attrInteger));
		}
		
		if(OutputRightSubject==1){
			bpattrList.add(new AttrType(AttrType.attrInteger));
			bpattrList.add(new AttrType(AttrType.attrInteger));
		}
		if(OutputRightObject==1){
			bpattrList.add(new AttrType(AttrType.attrInteger));
			bpattrList.add(new AttrType(AttrType.attrInteger));
		}
		bpattrList.add(new AttrType(AttrType.attrReal));
		bpattrList.add(new AttrType(AttrType.attrReal));
		if(level==2){
			bpattrList.add(new AttrType(AttrType.attrReal));	
		}
		AttrType[] bpattr = bpattrList.toArray(new AttrType[bpattrList.size()]);
		
		return bpattr ;
	}
	
	
	private FldSpec [] Query_projection(int[] LeftOutNodePositions, int OutputRightSubject, int OutputRightObject) {
		ArrayList<FldSpec> projList = new ArrayList<FldSpec>();
		if(level ==1){
	    	for (int i : LeftOutNodePositions) {
				if(i==1){
					projList.add(new FldSpec(new RelSpec(RelSpec.outer), 1));
					projList.add(new FldSpec(new RelSpec(RelSpec.outer), 2));
				}
				else if(i==2){
					projList.add(new FldSpec(new RelSpec(RelSpec.outer), 5));
					projList.add(new FldSpec(new RelSpec(RelSpec.outer), 6));
				}							
			}
	    	
	    	if(OutputRightSubject == 1){
				projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 1));
				projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 2));
			}
			
			if(OutputRightObject == 1){
				projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 5));
				projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 6));
			}
			projList.add(new FldSpec(new RelSpec(RelSpec.outer), 7));
			projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 7));
			
	    }
		
		
		if(level==2){
		int j = 0;
		int len = LeftOutNodePositions.length;
		for(int i=0; i<len ; i++){
			j= LeftOutNodePositions[i]*2 - 1;
			projList.add(new FldSpec(new RelSpec(RelSpec.outer), j));
			projList.add(new FldSpec(new RelSpec(RelSpec.outer), j+1));
		}
		
		if(OutputRightSubject == 1){
			projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 1));
			projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 2));
		}
		
		if(OutputRightObject == 1){
			projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 5));
			projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 6));
		}
		int current = lastBPLength-2;
		for (int k = 1; k <= level; k++) {
			projList.add(new FldSpec(new RelSpec(RelSpec.outer), ++current));
		}
		projList.add(new FldSpec(new RelSpec(RelSpec.innerRel), 7));
		}
		FldSpec[] proj = projList.toArray(new FldSpec[projList.size()]);
		
		return proj ;
	}
	
	private void Query2_CondExpr(CondExpr[] expr, CondExpr[] expr2, int JoinOnSubjectorObject,
			int BPjoinNodePosition,float ConfidenceFilterRHS) {
		int node = BPjoinNodePosition;
		if (cheatingCounter == 0) {
			if (BPjoinNodePosition > 1)
				BPjoinNodePosition++;
		}
		if(JoinOnSubjectorObject==0 &&  BPjoinNodePosition==1){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),2);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2);
		}
		if(JoinOnSubjectorObject==1 &&  BPjoinNodePosition==1){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),5);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),2);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),6);
		}
		if(JoinOnSubjectorObject==0 &&  BPjoinNodePosition==2){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3);//5
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),4);//6
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2);
		}
		if(JoinOnSubjectorObject==1 &&  BPjoinNodePosition==2){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),3);//5
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),5);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),4);//6
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),6);
		}
		if(JoinOnSubjectorObject==0 &&  BPjoinNodePosition==3){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),5);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),6);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2);
		}
		if(JoinOnSubjectorObject==1 &&  BPjoinNodePosition==3){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),5);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),5);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),6);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),6);
		}
		if(JoinOnSubjectorObject==0 &&  BPjoinNodePosition==4){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),7);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),8);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),2);
		}
		if(JoinOnSubjectorObject==1 &&  BPjoinNodePosition==4){
			expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),7);
		    expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),5);
		    expr[1].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),8);
		    expr[1].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),6);
		}
	    expr[0].next  = null;
	    expr[0].op    = new AttrOperator(AttrOperator.aopEQ);
	    expr[0].type1 = new AttrType(AttrType.attrSymbol);
	    expr[0].type2 = new AttrType(AttrType.attrSymbol);
	    expr[1].op    = new AttrOperator(AttrOperator.aopEQ);
	    expr[1].type1 = new AttrType(AttrType.attrSymbol);
	    expr[1].type2 = new AttrType(AttrType.attrSymbol);
	    expr[1].next  = null;
	   // expr[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),1);
	   // expr[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
	    
	    expr[2] = null;
	 
	    //expr2[0].next  = null;
	    //expr2[0].op    = new AttrOperator(AttrOperator.aopGE); 
	    //expr2[0].type1 = new AttrType(AttrType.attrSymbol);
	    //expr2[0].type2 = new AttrType(AttrType.attrSymbol);   
	    //expr2[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),2);
	    //expr2[0].operand2.symbol = new FldSpec (new RelSpec(RelSpec.innerRel),1);
	    
	    expr2[0].op   = new AttrOperator(AttrOperator.aopGE);
	    expr2[0].next = null;
	    expr2[0].type1 = new AttrType(AttrType.attrSymbol);
	    expr2[0].type2 = new AttrType(AttrType.attrReal);
	    expr2[0].operand1.symbol = new FldSpec (new RelSpec(RelSpec.outer),7);
	    expr2[0].operand2.real = ConfidenceFilterRHS;
	 
	    expr2[1] = null; 
	  }

	public   IndexScan getTriples(RID sRID, RID pRID, RID oRID,
			float confidence, RdbIndexType IndexOption)
			throws InvalidTypeException, InvalidTupleSizeException,
			IOException, FieldNumberOutOfBoundException {

		KeyCombine combine = new KeyCombine();
		Triple triple = new Triple();
		triple.addTriple(sRID, pRID, oRID, confidence);
		String searchKey = combine.getStrKey(triple, IndexOption);

		// @TODO: for an index option with C,E or P, you will not have any ':'
		// in the key.
		String endKey = null;
		String endKey1 = searchKey.replaceFirst(":", ";");
		switch (IndexOption) {
		case SPO:
			String endKey2 = endKey1.replaceFirst(":", ";");
			endKey2 = endKey2.replaceFirst(";", ":");
			if (isRIDModified(oRID))
				endKey = searchKey;
			else if (isRIDModified(pRID))
				endKey = endKey2;
			else
				endKey = endKey1;
			break;
		case PC:
			endKey = endKey1;
			System.out.println(endKey);
			break;
		case OC:
			endKey = endKey1;
			break;
		case SO:
			endKey = searchKey;
			break;
		case PO:
			endKey = searchKey;
			System.out.println(endKey);
			break;
		case SC :
			endKey=endKey1;
			break;
		case C :
			endKey="1.0";
		}

		// String endKey = searchKey.replace(':', ';');

		AttrType[] attrType = new AttrType[7];
		attrType[0] = new AttrType(AttrType.attrInteger);
		attrType[1] = new AttrType(AttrType.attrInteger);
		attrType[2] = new AttrType(AttrType.attrInteger);
		attrType[3] = new AttrType(AttrType.attrInteger);
		attrType[4] = new AttrType(AttrType.attrInteger);
		attrType[5] = new AttrType(AttrType.attrInteger);
		attrType[6] = new AttrType(AttrType.attrReal);
		short[] attrSize = null;

		CondExpr[] expr = new CondExpr[3];
		expr[0] = new CondExpr();
		expr[0].op = new AttrOperator(AttrOperator.aopGE);
		expr[0].type1 = new AttrType(AttrType.attrSymbol);
		expr[0].type2 = new AttrType(AttrType.attrString);
		expr[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1);
		expr[0].operand2.string = searchKey;
		expr[0].next = null;
		expr[1] = new CondExpr();
		expr[1].op = new AttrOperator(AttrOperator.aopLE);
		expr[1].type1 = new AttrType(AttrType.attrSymbol);
		expr[1].type2 = new AttrType(AttrType.attrString);
		expr[1].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1);
		expr[1].operand2.string = endKey;
		expr[1].next = null;
		expr[2] = null;

		System.out.println("Looking for Triples between " + searchKey + " and "
				+ endKey);

		FldSpec[] projlist = new FldSpec[1];
		RelSpec rel = new RelSpec(RelSpec.outer);
		projlist[0] = new FldSpec(rel, 1);

		IndexScan iscan = null;
		try {
			iscan = new IndexScan(new IndexType(IndexType.B_Index), "triples" + counter,
					"BTreeIndex_" + IndexOption + counter, attrType, attrSize, 7, 1,
					projlist, expr, 1, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return iscan;
	}
	

	private   RID getTripleRID(Triple triple) throws IndexException,
			UnknownKeyTypeException, IOException, InvalidTypeException,
			InvalidTupleSizeException, FieldNumberOutOfBoundException {

		KeyCombine combine = new KeyCombine();

		AttrType[] attrType = new AttrType[7];
		attrType[0] = new AttrType(AttrType.attrInteger);
		attrType[1] = new AttrType(AttrType.attrInteger);
		attrType[2] = new AttrType(AttrType.attrInteger);
		attrType[3] = new AttrType(AttrType.attrInteger);
		attrType[4] = new AttrType(AttrType.attrInteger);
		attrType[5] = new AttrType(AttrType.attrInteger);
		attrType[6] = new AttrType(AttrType.attrReal);
		short[] attrSize = null;

		CondExpr[] expr = new CondExpr[2];
		expr[0] = new CondExpr();
		expr[0].op = new AttrOperator(AttrOperator.aopEQ);
		expr[0].type1 = new AttrType(AttrType.attrSymbol);
		expr[0].type2 = new AttrType(AttrType.attrString);
		expr[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1);
		expr[0].operand2.string = combine.getStrKey(triple, RdbIndexType.SPO);
		expr[0].next = null;
		expr[1] = null;

		System.out.println("Looking for Triple with key: "
				+ combine.getStrKey(triple, RdbIndexType.SPO));

		FldSpec[] projlist = new FldSpec[1];
		RelSpec rel = new RelSpec(RelSpec.outer);
		projlist[0] = new FldSpec(rel, 1);

		IndexScan iscan = null;
		try {
			iscan = new IndexScan(new IndexType(IndexType.B_Index), "triples" + counter,
					"BTreeIndex_" + RdbIndexType.SPO + counter, attrType, attrSize, 7, 1,
					projlist, expr, 1, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		RID _rid = new RID();
		iscan.get_next(_rid);
		System.out.println(_rid.pageNo+" , "+_rid.slotNo);
		iscan.close();
		return _rid;
	}

	private   String getLabelRID(String HeapFileName, String Label,
			String IndexName, RID rid) throws Exception {

		AttrType[] attrType = new AttrType[1];
		attrType[0] = new AttrType(AttrType.attrString);
		short[] attrSize = new short[1];
		attrSize[0] = 50;
		Tuple tuple;
		StringLabel lbl = new StringLabel();

		CondExpr[] expr = new CondExpr[2];
		expr[0] = new CondExpr();
		expr[0].op = new AttrOperator(AttrOperator.aopEQ);
		expr[0].type1 = new AttrType(AttrType.attrSymbol);
		expr[0].type2 = new AttrType(AttrType.attrString);
		expr[0].operand1.symbol = new FldSpec(new RelSpec(RelSpec.outer), 1);
		expr[0].operand2.string = Label;
		expr[0].next = null;
		expr[1] = null;

		FldSpec[] projlist = new FldSpec[1];
		RelSpec rel = new RelSpec(RelSpec.outer);
		projlist[0] = new FldSpec(rel, 1);

		IndexScan iscan = null;
		try {
			iscan = new IndexScan(new IndexType(IndexType.B_Index),
					HeapFileName, IndexName, attrType, attrSize, 1, 1,
					projlist, expr, 1, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

		RID _rid = new RID();

		tuple = iscan.get_next(_rid);
		iscan.close();
		rid.copyRid(_rid);
		if (tuple != null)
			return tuple.getStrFld(1);
		return null;
	}

	public   String getObjectRID(String object, RID rid) throws Exception {
		return getSubjectRID(object, rid);
	}

	public   String getPredicateRID(String predicate, RID rid)
			throws Exception {
		return getLabelRID("predicates" + counter, predicate, "BTreeIndex_"
				+ RdbIndexType.P + counter, rid);
	}
	
	
	public void lifeLine (Tuple t, AttrType []format) throws InvalidSlotNumberException, InvalidTupleSizeException, HFException, HFDiskMgrException, HFBufMgrException, Exception {
		int pno = 0;
		int slot = 0;
		RID rid;
		StringLabel entityTuple;
		String entity;
		float conf;
		for (int i = 0; i < format.length; i++) {
			if (format [i].attrType == AttrType.attrInteger) {
				pno = t.getIntFld(i+1);
			if (format [++i].attrType == AttrType.attrInteger)
				slot = t.getIntFld(i+1);
			rid = new RID (new PageId(pno), slot);
			//System.out.println("RID = " + rid);
			try {
				entityTuple = entityHeap.getRecord(rid);
			} catch (Exception e) {
				entityTuple = predicateHeap.getRecord(rid);
			}
			entity = entityTuple.getStrFld(1);
			//System.out.print(entity + "  ");
			}
			else {
				conf = t.getFloFld(i+1);
			//	System.out.println(conf);
			}
		}
		
	}

	public static  boolean isRIDModified(RID rid) {
		if (rid.pageNo.pid != 0 || rid.slotNo != 0)
			return true;
		return false;
	}
	
	public void cleanup () throws IOException {
		Runtime.getRuntime().exec("rm " + dbName);
	}

	public   void insertTriple(String subject, String predicate,
			String object, float confidence, RdbIndexType indexOption)
			throws Exception {

		if(subject.length() > 49)
			subject = subject.substring(0,48 );
		if(predicate.length() > 49)
			predicate = predicate.substring(0,48 );
		if(object.length() > 49)
			object = object.substring(0,48);
		boolean blindInsert = false;
		RID sRID = null, pRID = null, oRID = null;
		RID seid = null, pid = null, oeid = null;
		Triple triple;
		RID rid;
		Tuple tuple;
//		System.out.println("Creating String labels");
		// Get the three RIDCS
//		System.out.println("Checking if subject aleady exists");
		sRID = new RID();
		getSubjectRID(subject, sRID);
		if (isRIDModified(sRID))
			System.out.println("Subject ID already exists in database");
		else {
			System.out.println("Subject Id doesn't exist");
			blindInsert = true;
		}
		oRID = new RID();
		getObjectRID(object, oRID);
//		System.out.println("Checking if object aleady exists");
		if (isRIDModified(oRID))
			System.out.println("Object ID already exists in database");
		else {
			System.out.println("Object Id doesn't exist");
			blindInsert = true;
		}
		pRID = new RID();
		getPredicateRID(predicate, pRID);
//		System.out.println("Checking if predicate aleady exists");
		if (isRIDModified(pRID))
			System.out.println("Predicate ID already exists in database");
		else {
			System.out.println("Predicate Id doesn't exist");
			blindInsert = true;
		}
		if (!blindInsert) {
			// Check if an update needs to be made
			System.out
					.println("Checking if a record with the same combination exists...");
			triple = new Triple();
			triple.addTriple(sRID, pRID, oRID, confidence);
			
			rid = getTripleRID(triple);
			if (isRIDModified(rid)) {
				System.out
						.println("Oops! There is an entry with the same combination. Lets check if confidence has reduced");
				tuple = tripleHeap.getRecord(rid, false);
				triple.tupleCopy(tuple);
				if (triple.getConfidence() > confidence) {
					System.out
							.println("The confidence value is low. Need to be updated");
					triple.setConfidence(confidence);
					tripleHeap.updateRecord(rid, triple, false);
					System.out.println("Updation complete");
				} else
					System.out.println("I do nothing here");
				return;
			}
		}
		System.out.println("Insertion begins");
		StringLabel subject_label = new StringLabel();
		StringLabel predicate_label = new StringLabel();
		StringLabel object_label = new StringLabel();
		if (!isRIDModified(sRID)) {
//			System.out.println("Adding string to labels");
//			System.out.println(subject);
			subject_label.addLabel(subject);
			seid = entityHeap.insertRecord(subject_label.getTupleByteArray());
			addToIndex(RdbIndexType.E, subject_label, seid);
//			System.out.println("Subject ID is:" + seid);
		} else {
			seid = sRID;
		}
		if (!isRIDModified(pRID)) {
//			System.out.println("Adding predicate to labels");
			predicate_label.addLabel(predicate);
			pid = predicateHeap.insertRecord(predicate_label
					.getTupleByteArray());
			addToIndex(RdbIndexType.P, predicate_label, pid);
//			System.out.println("Predicate ID is:" + pid);
		} else
			pid = pRID;
		if (!isRIDModified(oRID)) {
			if (!object.equals(subject)) {
//				System.out.println("Adding object to labels");
				object_label.addLabel(object);
				oeid = entityHeap.insertRecord(object_label.getTupleByteArray());
				addToIndex(RdbIndexType.E, object_label, oeid);
//				System.out.println("Object ID is:" + oeid);
			} else {
				oeid = seid;
			}
		} else
			oeid = oRID;
		System.out.println("Inserting records");
		triple = new Triple();
		triple.addTriple(seid, pid, oeid, confidence);
		rid = tripleHeap.insertRecord(triple.getTupleByteArray());
		// addToIndex(RdbIndexType.SPO, triple, rid);
		addToIndex(indexOption, triple, rid);
		// getTripleRID(triple);
		System.out.println("Triple ID is:" + rid);

//		System.out.println("Reading the inserted data.....");
//		tuple = tripleHeap.getRecord(rid);
//		triple.tupleCopy(tuple);
//		EID _seid = triple.getSubjectID();
//		PID _pid = triple.getPredicateID();
//		EID _oeid = triple.getObjectID();
//		subject_label = entityHeap.getRecord(_seid);
//		predicate_label = predicateHeap.getRecord(_pid);
//		object_label = entityHeap.getRecord(_oeid);
//		System.out.println(subject_label + "," + predicate_label + ","
//				+ object_label);
		
//		stats.setNo_of_files((PCounter.get_no_of_files() - no_of_files)+stats.getNo_of_files());
//		stats.setPagesAllocated((PCounter.getPagesAllocated() - pagesAllocated)+stats.getPagesAllocated());
//		stats.setPagesDeallocated((PCounter.getPagesDeallocated() - pagesDeallocated)+stats.getPagesDeallocated());
//		stats.setReadCounter((PCounter.getreadCounter() - readCounter)+stats.getReadCounter());
//		stats.setWriteCounter((PCounter.getwriteCounter() - writeCounter)+stats.getWriteCounter());
		
		//log.write("After insert :");
		//log.write(PCounter.getStats());

	}

	public   void deleteIndex(RdbIndexType indexOption, Tuple temp, RID rid,
			String filename) throws GetFileEntryException, PinPageException,
			ConstructPageException, InvalidTypeException,
			InvalidTupleSizeException, IOException,
			FieldNumberOutOfBoundException, KeyTooLongException,
			KeyNotMatchException, LeafInsertRecException,
			IndexInsertRecException, UnpinPageException, NodeNotMatchException,
			ConvertException, DeleteRecException, IndexSearchException,
			IteratorException, LeafDeleteException, InsertException, DeleteFashionException, LeafRedistributeException, RedistributeException, InsertRecException, FreePageException, RecordNotFoundException, IndexFullDeleteException {
		StringLabel lbl = null;
		Triple triple = null;
		String key = null;

		if (indexOption == RdbIndexType.E || indexOption == RdbIndexType.P) {
			lbl = new StringLabel();
			lbl.tupleCopy(temp);
		} else {
			triple = new Triple();
			triple.tupleCopy(temp);
		}
		KeyCombine kc = new KeyCombine();
		if (indexOption == RdbIndexType.E || indexOption == RdbIndexType.P)
			key = lbl.getStrFld(1);
		else
			key = kc.getStrKey(triple, indexOption);
		BTreeFile btf = new BTreeFile(filename);
		btf.Delete(new StringKey(key), rid);
		System.out.println("Deleted Key " + key + " from Index " + filename);

	}

	
	
	
	public   void addIndex(RdbIndexType indexOption, Tuple temp, RID rid,
			String filename) throws GetFileEntryException, PinPageException,
			ConstructPageException, InvalidTypeException,
			InvalidTupleSizeException, IOException,
			FieldNumberOutOfBoundException, KeyTooLongException,
			KeyNotMatchException, LeafInsertRecException,
			IndexInsertRecException, UnpinPageException, NodeNotMatchException,
			ConvertException, DeleteRecException, IndexSearchException,
			IteratorException, LeafDeleteException, InsertException {
		StringLabel lbl = null;
		Triple triple = null;
		String key = null;

		if (indexOption == RdbIndexType.E || indexOption == RdbIndexType.P) {
			lbl = new StringLabel();
			lbl.tupleCopy(temp);
		} else {
			triple = new Triple();
			triple.tupleCopy(temp);
		}
		KeyCombine kc = new KeyCombine();
		if (indexOption == RdbIndexType.E || indexOption == RdbIndexType.P)
			key = lbl.getStrFld(1);
		else
			key = kc.getStrKey(triple, indexOption);
		BTreeFile btf = new BTreeFile(filename);
		btf.insert(new StringKey(key), rid);
		System.out.println("Added Key " + key + " to Index " + filename);
	}

	public   void addToIndex(RdbIndexType indexOption, Tuple temp, RID rid)
			throws InvalidTypeException, InvalidTupleSizeException,
			FieldNumberOutOfBoundException, GetFileEntryException,
			PinPageException, ConstructPageException, KeyTooLongException,
			KeyNotMatchException, LeafInsertRecException,
			IndexInsertRecException, UnpinPageException, NodeNotMatchException,
			ConvertException, DeleteRecException, IndexSearchException,
			IteratorException, LeafDeleteException, InsertException,
			IOException {
		String filename = null;
		RdbIndexType[] array = { RdbIndexType.SO, RdbIndexType.PO,
				RdbIndexType.SPO, RdbIndexType.PSO, RdbIndexType.SC,
				RdbIndexType.PC, RdbIndexType.OC, RdbIndexType.C };
		if (indexOption == RdbIndexType.ALL) {
			for (RdbIndexType type : array) {
				filename = "BTreeIndex" + "_" + type + counter;
				addIndex(type, temp, rid, filename);
			}
		} else {
			filename = "BTreeIndex" + "_" + indexOption + counter;
			addIndex(indexOption, temp, rid, filename);
		}
	}

	public   void createIndex(Heapfile heapFile, RdbIndexType indexOption)
			throws InvalidTypeException, InvalidTupleSizeException,
			IOException, FieldNumberOutOfBoundException {
		// create an scan on the heapfile
		Scan scan = null;
		boolean status = true;

		try {
			scan = new Scan(heapFile);
		} catch (Exception e) {
			status = false;
			e.printStackTrace();
			Runtime.getRuntime().exit(1);
		}

		// create the index file
		BTreeFile btf = null;
		String filename = "BTreeIndex" + "_" + indexOption + counter;
		System.out.println(filename);
		try {
			/* change the btree index on the column of your choice */
			btf = new BTreeFile(filename, AttrType.attrString, 192, 1/* delete */);
			// btf = new BTreeFile("BTreeIndex");
		} catch (Exception e) {
			status = false;
			e.printStackTrace();
			Runtime.getRuntime().exit(1);
		}

		System.out.println("BTreeIndex created successfully. :" + filename);

		RID rid = new RID();
		String key = null;
		Tuple temp = null;
		Triple triple = new Triple();
		// Tuple tup=new Tuple();
		StringLabel lbl = new StringLabel();
		try {
			temp = scan.getNext(rid);
		} catch (Exception e) {
			status = false;
			e.printStackTrace();
		}
		while (temp != null) {
			if (indexOption == RdbIndexType.E || indexOption == RdbIndexType.P) {
				lbl.tupleCopy(temp);
			} else
				triple.tupleCopy(temp);

			try {
				KeyCombine kc = new KeyCombine();
				if (indexOption == RdbIndexType.E
						|| indexOption == RdbIndexType.P)
					key = lbl.getStrFld(1);
				else
					key = kc.getStrKey(triple, indexOption);
			} catch (Exception e) {
				status = false;
				e.printStackTrace();
			}

			try {
				btf.insert(new StringKey(key), rid);
			} catch (Exception e) {
				status = false;
				e.printStackTrace();
			}

			try {
				temp = scan.getNext(rid);
			} catch (Exception e) {
				status = false;
				e.printStackTrace();
			}
		}

		// close the file scan
		scan.closescan();

		System.out.println("BTreeIndex file created successfully.\n");
	}

	public   void createTempTable() throws HFException,
			HFBufMgrException, HFDiskMgrException, IOException, InvalidTypeException, InvalidTupleSizeException {
		temporaryHeap = new Heapfile("temporaryHeap");
		sutil = new SortUtility(this);
	}
	
	public   void createTempTable(int node, int total_nodes) throws HFException,
	HFBufMgrException, HFDiskMgrException, IOException, InvalidTypeException, InvalidTupleSizeException {
		temporaryHeap = new Heapfile("temporaryHeap");
		sutil = new SortUtility(this, node, total_nodes);
}
	

	private   void addTemporaryData(String subject, String predicate,
			String object) throws InvalidTypeException,
			InvalidTupleSizeException, IOException,
			FieldNumberOutOfBoundException, InvalidSlotNumberException,
			SpaceNotAvailableException, HFException, HFBufMgrException,
			HFDiskMgrException {
		TemporaryTriple tt = new TemporaryTriple();
		// tt.addTriple(subject, predicate, object);

	}

	public   Sort getTemporarySortStream(int buf_size)
			throws FileScanException, TupleUtilsException, InvalidRelation,
			IOException, SortException, JoinsException,
			InvalidTupleSizeException, InvalidTypeException,
			PageNotReadException, PredEvalException, UnknowAttrType,
			FieldNumberOutOfBoundException, WrongPermat {
		short numFlds = 1;
		short[] strSizes = { TEMPORARY_TRIPLE_SIZE };
		AttrType[] types = { new AttrType(AttrType.attrString) };
		int SORTPGNUM = 12;
		if (buf_size > 1)
			SORTPGNUM = buf_size;

		System.out.println("BUFFER_PAGE SIZE: " + SORTPGNUM);

		FldSpec[] projlist = new FldSpec[1];
		RelSpec rel = new RelSpec(RelSpec.outer);
		projlist[0] = new FldSpec(rel, 1);

		FileScan fScan = new FileScan("temporaryHeap", types, strSizes,
				(short) 1, 1, projlist, null);

		// Tuple t = fScan.get_next();
		// System.out.println("Scan tuple is " + t.getStrFld(1));

		Sort sort = new Sort(types, (short) 1, strSizes, fScan, 1,
				new TupleOrder(TupleOrder.Ascending), 157, SORTPGNUM);

		return sort;
	}
	
	public DuplElim getDuplicateEliminatedSortStream(int buf_size)
			throws FileScanException, TupleUtilsException, InvalidRelation,
			IOException, SortException, JoinsException,
			InvalidTupleSizeException, InvalidTypeException,
			PageNotReadException, PredEvalException, UnknowAttrType,
			FieldNumberOutOfBoundException, WrongPermat, DuplElimException {
		short numFlds = 1;
		short[] strSizes = { TEMPORARY_TRIPLE_SIZE };
		AttrType[] types = { new AttrType(AttrType.attrString) };
		int SORTPGNUM = 12;
		if (buf_size > 1)
			SORTPGNUM = buf_size;

		System.out.println("BUFFER_PAGE SIZE: " + SORTPGNUM);

		FldSpec[] projlist = new FldSpec[1];
		RelSpec rel = new RelSpec(RelSpec.outer);
		projlist[0] = new FldSpec(rel, 1);

		FileScan fScan = new FileScan("temporaryHeap", types, strSizes,
				(short) 1, 1, projlist, null);

		// Tuple t = fScan.get_next();
		// System.out.println("Scan tuple is " + t.getStrFld(1));

		Sort sort = new Sort(types, (short) 1, strSizes, fScan, 1,
				new TupleOrder(TupleOrder.Ascending), 157, SORTPGNUM);
		
		DuplElim de = new DuplElim(types, (short) 1, strSizes, sort, SORTPGNUM, true);

		return de;
	}
	

	public   void destroyTempTable() throws InvalidSlotNumberException,
			FileAlreadyDeletedException, InvalidTupleSizeException,
			HFBufMgrException, HFDiskMgrException, IOException {
		temporaryHeap.deleteFile();
	}

	public   void deleteTriple(String subjectFilter,
			String predicateFilter, String objectFilter) throws Exception {
				
		if (subjectFilter != null && predicateFilter != null
				&& objectFilter != null) {
			RID sRID = new RID();
			String subject = getSubjectRID(subjectFilter, sRID);
			RID pRID = new RID();
			String predicate = getPredicateRID(predicateFilter, pRID);
			RID oRID = new RID();
			String object = getObjectRID(objectFilter, oRID);
			IndexScan scan = getTriples(sRID, pRID, oRID, (float) 0.0,
					RdbIndexType.SPO);
			String filename;
			RID _rid = new RID();
			scan.get_next(_rid, true);
			scan.close();
			if (DEBUG)
				System.out.println("Matched rid in iface:" + _rid);
			RdbIndexType[] array = { RdbIndexType.SO, RdbIndexType.PO,
					RdbIndexType.SPO, 
					RdbIndexType.PSO, RdbIndexType.SC,
					RdbIndexType.PC, RdbIndexType.OC, RdbIndexType.C };
							
				
			//while (isRIDModified(_rid)) {
				Tuple temp = tripleHeap.getRecord(_rid,false);
				if(temp!=null){
				for (RdbIndexType type : array) {
					filename = "BTreeIndex" + "_" + type + counter;
					deleteIndex(type, temp, _rid, filename);
				}
				tripleHeap.deleteRecord(_rid);
				}
				else{
					System.out.println("no data matched");
				}
				//scan.get_next(_rid, true);
			//}
		}
	}

	public   void deleteEntity(String entity) throws Exception {
		RID sRID = new RID();
		String subject = getSubjectRID(entity, sRID);
		RID pRID = new RID();
		RID oRID = new RID();
		String filename;
		IndexScan scan = getTriples(sRID, pRID, oRID, (float) 0.0,
				RdbIndexType.SC);
		RID _rid = new RID();
		scan.get_next(_rid, true);
		RdbIndexType[] array = { RdbIndexType.SO, RdbIndexType.PO,
				RdbIndexType.SPO,
				RdbIndexType.PSO,
				RdbIndexType.SC,
				RdbIndexType.PC, RdbIndexType.OC, RdbIndexType.C 
		};
		while (isRIDModified(_rid))
		{
			scan.close();		
			if (DEBUG)
				System.out.println("Matched rid in iface:" + _rid);
									
				
			while (isRIDModified(_rid)) {
				Tuple temp = tripleHeap.getRecord(_rid, false);
				tripleHeap.deleteRecord(_rid);
				for (RdbIndexType type : array) {
					filename = "BTreeIndex" + "_" + type + counter;
					deleteIndex(type, temp, _rid, filename);
				}
				//deleteIndex(RdbIndexType.SPO, temp2, toDel, "BTreeIndex_SPO");
				scan = getTriples(sRID, pRID, oRID, (float) 0.0,
						RdbIndexType.SC);
				_rid = new RID();
				scan.get_next(_rid, true);
				//toDel = _rid;
			}
		}
		scan.close();
		System.out.println("Object entries deletion started");
		String object = getObjectRID(entity, oRID);
		sRID = new RID();
		pRID = new RID();
		scan = getTriples(sRID, pRID, oRID, (float) 0.0, RdbIndexType.OC);
		_rid = new RID();
		scan.get_next(_rid, true);
		if (DEBUG)
			System.out.println("Matched rid in iface:" + _rid);
		while (isRIDModified(_rid)) {
			scan.close();			
			if (DEBUG)
				System.out.println("Matched rid in iface:" + _rid);			
				
			while (isRIDModified(_rid)) {
				Tuple temp = tripleHeap.getRecord(_rid,false);
				tripleHeap.deleteRecord(_rid);
				for (RdbIndexType type : array) {
					filename = "BTreeIndex" + "_" + type + counter;
					try {
					deleteIndex(type, temp, _rid, filename);
					} catch (Exception e) {
						//This could mean the triple was of form
						//data predicate data
						//so it was already deleted for the subject
						//part
					}
				}
				//deleteIndex(RdbIndexType.SPO, temp2, toDel, "BTreeIndex_SPO");
				scan = getTriples(sRID, pRID, oRID, (float) 0.0,
						RdbIndexType.OC);
				_rid = new RID();
				scan.get_next(_rid, true);
				//toDel = _rid;
			}
		}
		scan.close ();
		Tuple temp = entityHeap.getRecord(oRID);
		deleteIndex(RdbIndexType.E, temp, oRID, "BTreeIndex" + "_" + RdbIndexType.E + counter);
		entityHeap.deleteRecord(oRID);
		scan.close();
	}

	private   void printData(String subject, String predicate,
			String object, Float confidence) {
		System.out.println(subject + " " + predicate + " " + object + " "
				+ confidence);
	}
	
	public String getOrderby (RdbIndexType option) {
		switch (option) {
		case SPO:
			return "Subject, predicate and object";
		case PSO:
			return "Predicate, subject and object";
		case SC:
			return "Subject and confidence";
		case OC:
			return "object and confidence";
		case PC:
			return "Predicate and confidence";
		case C:
			return "confidence";
		}
		return "Unknown option";
	}
	
	public void querySystemNaive (String subjectFilter,
			String predicateFilter, String objectFilter, Float confidence,
			RdbIndexType orderOption, int buf_size)
			throws InvalidSlotNumberException, HFException, HFDiskMgrException,
			HFBufMgrException, Exception {
		Scan scan = null;
		createTempTable();
		
		log.write("Query\n");
		log.write("=====\n");
		log.write("Subject Filter:" + subjectFilter + "\n");
		log.write("object Filter:" + objectFilter + "\n");
		log.write("Confidence Filter:" + confidence.toString() + "\n");
		log.write("Order by option:" + getOrderby(orderOption) + "\n");
		
		long start = System.nanoTime();
		
		try {
			scan = new Scan(tripleHeap);
		} catch (Exception e) {
			e.printStackTrace();
			Runtime.getRuntime().exit(1);
		}
		
		RID rid = new RID();
		String key = null;
		Tuple temp = null;
		Triple triple = new Triple();
		// Tuple tup=new Tuple();
		StringLabel subject = new StringLabel();
		StringLabel predicate = new StringLabel();
		StringLabel object = new StringLabel();
		Float conf;
		SortUtility sutil = new SortUtility(this);
		try {
			temp = scan.getNext(rid);
		} catch (Exception e) {
			e.printStackTrace();
		}
		while (temp != null) {
			triple.tupleCopy(temp);
			subject = entityHeap.getRecord(triple.getSubjectID());
			if (subject.getLabel().equals(subjectFilter)) {
				if (DEBUG)
					System.out.println("Matched record");
				sutil.formatTriple(triple, orderOption);
			}
			try {
				temp = scan.getNext(rid);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	
		String[] dataprintable = sutil.getNextSortedTriple(buf_size);
		while (dataprintable != null) {
			log.write(dataprintable[0].trim() + "," + dataprintable[1].trim() + "," + dataprintable[2].trim() + "," + dataprintable[3].trim());
			dataprintable = sutil.getNextSortedTriple(buf_size);
		}
		long end = System.nanoTime();
		long time = end - start;
		log.write("Total Time for sorting (in nanoseconds)"+time);
		destroyTempTable();

		// close the file scan
		scan.closescan();
		
		
	}

	public  void querySystem(String subjectFilter,
			String predicateFilter, String objectFilter, Float confidence,
			RdbIndexType orderOption, int buf_size)
			throws InvalidSlotNumberException, HFException, HFDiskMgrException,
			HFBufMgrException, Exception {
		Iterator itr = query(subjectFilter, predicateFilter, objectFilter, confidence, orderOption, buf_size);
		if(itr instanceof IndexScan){
			IndexScan i = (IndexScan) itr;
			populateTemp(i, confidence, orderOption);
		}
		
		/*
		 * switch(orderOption){ case SPO: String data; if (flag) { stream =
		 * getTemporarySortStream(); t = stream.get_next(); while (t != null) {
		 * data = t.getStrFld(1); String [] triple_str = data.split("\\^");
		 * printData(triple_str [0], triple_str [1], triple_str [2],
		 * Float.parseFloat(triple_str [3])); t = stream.get_next(); } } }
		 */
		String[] dataprintable = null;
		/*
		 * for(int i=1;i<=rcount;i++){
		 * dataprintable=SortUtility.getNextSortedTriple(buf_size); for(int
		 * j=0;j<4;j++){ System.out.print(dataprintable[j].trim()+" , "); }
		 * System.out.print("\n"); }
		 */
		
		long start = System.nanoTime();
		dataprintable = sutil.getNextSortedTriple(buf_size);
		int length = 0;
		while (dataprintable != null) {
			log.write(dataprintable[0].trim() + "," + dataprintable[1].trim() + "," + dataprintable[2].trim() + "," + dataprintable[3].trim());
			dataprintable = sutil.getNextSortedTriple(buf_size);
		}
		long end = System.nanoTime();
		long time = end - start;
		log.write("Total Time for sorting (in nanoseconds)"+time);
		destroyTempTable();
	}
		
	private void populateTemp(IndexScan scan, Float confidence, RdbIndexType orderOption) throws InvalidSlotNumberException, Exception{
		Float conf = null;
		Tuple tuple;
		Triple triple = new Triple();
		RID _rid = new RID();
		boolean flag = false;
		createTempTable();
		int rcount = 0;
		Tuple t = scan.get_next(_rid, true);
		if (confidence == null)
			confidence = (float) 0.0;
		if (DEBUG)
		System.out.println("Matched rid in iface:" + _rid);
	log.write("**** File querying for index option : SPO with only subject,object & predicate filter ****");
	long start = System.nanoTime();
	while (isRIDModified(_rid)) {
		flag = true;
		tuple = tripleHeap.getRecord(_rid, false);
		triple.tupleCopy(tuple);
		if (DEBUG)
			triple.printTuple();
		conf = triple.getConfidence();
		if (conf >= confidence || true) {
			rcount++;
			sutil.formatTriple(triple, orderOption);

		}
		t = scan.get_next(_rid, true);
		System.out.println("next rid "+_rid);
	}
	
	long end = System.nanoTime();
	long time = end - start;
	log.write("Total Time for querying using index SPO with subject, object & predicate filter (in nanoseconds)"+time);
	scan.close ();
	if (rcount == 0) {
		System.out.println("No Data Found");
	} else {
		System.out.println(rcount + " Record(s) matched");
	}
	}
	
	public Iterator query(String subjectFilter,
			String predicateFilter, String objectFilter, Float confidence,
			RdbIndexType orderOption, int buf_size)
			throws InvalidSlotNumberException, HFException, HFDiskMgrException,
			HFBufMgrException, Exception {
		log.write("Query\n");
		log.write("=====\n");
		log.write("Subject Filter:" + subjectFilter + "\n");
		log.write("object Filter:" + objectFilter + "\n");
		log.write("Confidence Filter:" + confidence.toString() + "\n");
		log.write("Order by option:" + getOrderby(orderOption) + "\n");
		if (DEBUG)
			System.out.println("Filters are :" + subjectFilter + ","
					+ predicateFilter + "," + objectFilter + "," + confidence);
		RID sRID = null, oRID = null, pRID = null;
		String subject = null, predicate = null, object = null;
		IndexScan scan = null;
		if (confidence == null)
			confidence = (float) 0.0;

		if (subjectFilter != null && predicateFilter != null
				&& objectFilter != null) {
			sRID = new RID();
			subject = getSubjectRID(subjectFilter, sRID);
			pRID = new RID();
			predicate = getPredicateRID(predicateFilter, pRID);
			oRID = new RID();
			object = getObjectRID(objectFilter, oRID);
			scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.SPO);
			System.out.println("scanned data using SPO Index");

		} else if (subjectFilter != null && predicateFilter != null) {
			sRID = new RID();
			getSubjectRID(subjectFilter, sRID);
			pRID = new RID();
			getPredicateRID(predicateFilter, pRID);
			oRID = new RID();
			if (isRIDModified(sRID) || isRIDModified(pRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence,
						RdbIndexType.SPO);
			}
			System.out.println("scanned data using SPO Index");
		}

		else if (objectFilter != null && predicateFilter != null) {
			sRID = new RID();
			pRID = new RID();
			predicate=getPredicateRID(predicateFilter, pRID);
			oRID = new RID();
			object=getObjectRID(objectFilter, oRID);
			//if (isRIDModified(oRID) || isRIDModified(pRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.PO);
			//}
			
			System.out.println("scanned data using PO Index");
		}

		else if (subjectFilter != null && objectFilter != null) {
			sRID = new RID();
			getSubjectRID(subjectFilter, sRID);
			pRID = new RID();
			oRID = new RID();
			getObjectRID(objectFilter, oRID);
			if (isRIDModified(sRID) || isRIDModified(oRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.SO);
				}
			System.out.println("scanned data using SO Index");

		} else if (subjectFilter != null) {
			sRID = new RID();
			getSubjectRID(subjectFilter, sRID);
			pRID = new RID();
			oRID = new RID();
			if (isRIDModified(sRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence,
						RdbIndexType.SPO);
			}
			System.out.println("scanned data using SPO Index");
		}

		else if (predicateFilter != null) {
			sRID = new RID();
			pRID = new RID();
			getPredicateRID(predicateFilter, pRID);
			oRID = new RID();
			if (isRIDModified(pRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.PC);}
			System.out.println("scanned data using PC Index");

		} else if (objectFilter != null) {
			sRID = new RID();
			pRID = new RID();
			oRID = new RID();
			getObjectRID(objectFilter, oRID);
			if (isRIDModified(oRID)) {
				scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.OC);}
			System.out.println("scanned data using OC Index");
		}

		else if (confidence != null) {
			sRID = new RID();
			pRID = new RID();
			oRID = new RID();
			scan = getTriples(sRID, pRID, oRID, confidence, RdbIndexType.C);
			System.out.println("scanned data using C Index");
		}
		
			return scan;
		
	}
	
	public void querySystemForJoinTHF(String subjectFilter,
			String predicateFilter, String objectFilter, Float confidence,
			RdbIndexType orderOption, int buf_size) throws JoinsException, IndexException, InvalidTupleSizeException, InvalidTypeException, PageNotReadException, TupleUtilsException, PredEvalException, SortException, LowMemException, UnknowAttrType, UnknownKeyTypeException, Exception{
		Iterator itr = query(subjectFilter, predicateFilter, objectFilter, confidence, orderOption, buf_size);
		
		if(itr instanceof IndexScan){
			IndexScan i = (IndexScan) itr;
			Triple triple = new Triple();
			THFHeap [cheatingCounter] = new Heapfile("THFHeap"+cheatingCounter);
			RID _rid = new RID();
			Tuple t = i.get_next(_rid, true);
			if(t!= null){
				System.out.println("temp filter heap file created.");
			}
			int count=0;
			while(isRIDModified(_rid)){
				Tuple temp = tripleHeap.getRecord(_rid, false);
				triple.tupleCopy(temp);
				THFHeap[cheatingCounter].insertRecord(temp.getTupleByteArray());
				t = i.get_next(_rid, true);
				count++;
			}
			
			System.out.println("Records written in temp heap after filter"+count);
			
		}
	 	
	}
	
	public Iterator querySystemForJoin(String subjectFilter,
			String predicateFilter, String objectFilter, Float confidence,
			RdbIndexType orderOption, int buf_size)
			throws InvalidSlotNumberException, HFException, HFDiskMgrException,
			HFBufMgrException, Exception {
		Iterator itr = query(subjectFilter, predicateFilter, objectFilter, confidence, orderOption, buf_size);
		
		
		/*AttrType [] Tripletypes = {
			      new AttrType(AttrType.attrInteger), 
			      new AttrType(AttrType.attrInteger), 
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrInteger),
			      new AttrType(AttrType.attrReal) 
			    };
		 FldSpec [] Sprojection = {
	    			new FldSpec(new RelSpec(RelSpec.outer), 1),
	    			new FldSpec(new RelSpec(RelSpec.outer), 2),
	    			new FldSpec(new RelSpec(RelSpec.outer), 3),
	    			new FldSpec(new RelSpec(RelSpec.outer), 4),
	    			new FldSpec(new RelSpec(RelSpec.outer), 5),
	    			new FldSpec(new RelSpec(RelSpec.outer), 6),
	    			new FldSpec(new RelSpec(RelSpec.outer), 7)
		 };
		
		Iterator trhiter=null; 
		
		try{
			trhiter = new FileScan("temptriple", Tripletypes, null,
					(short) 7, 7, Sprojection, null);
			 }catch(Exception e){e.printStackTrace();} */
		
	return itr;
	}

	public static void main(String args[]) throws Exception {
		// LabelHeapfile lfile = new LabelHeapfile ("file2");

		Interface3 I3 = new Interface3();
		I3.init ("testdb", NUMBUF, 0);
		I3.createIndex(I3.tripleHeap, RdbIndexType.SPO);
		I3.createIndex(I3.tripleHeap, RdbIndexType.PSO);
		I3.createIndex(I3.tripleHeap, RdbIndexType.SC);
		I3.createIndex(I3.tripleHeap, RdbIndexType.PC);
		I3.createIndex(I3.tripleHeap, RdbIndexType.OC);
		I3.createIndex(I3.tripleHeap, RdbIndexType.C);
		I3.createIndex(I3.tripleHeap, RdbIndexType.SO);
		I3.createIndex(I3.tripleHeap, RdbIndexType.PO);
		I3.createIndex(I3.entityHeap, RdbIndexType.E);
		I3.createIndex(I3.predicateHeap, RdbIndexType.P);

		String[] dataval = null;
		String[] dataval2 = null;
		System.out.println("Please provide the argument for batch insert: \n");

		try {
			String datafilename = "//home//indrani//Downloads//phase2.txt";
			FileReader f = new FileReader(datafilename);

			// InputStreamReader IsR=new InputStreamReader(System.in);
			// FileReader f=new FileReader();
			BufferedReader in = new BufferedReader(f);
			String str;
			while ((str = in.readLine()) != null) {
				try {
					System.out.println(str);
					dataval = str.split(":");
					System.out.println(dataval[1] + " , " + dataval[2]);
					dataval2 = dataval[3].split("\\s+");
					String confidence = dataval2[1];
					System.out.println(dataval2[0] + " , " + dataval2[1]);
					I3.insertTriple(dataval[1].trim(), dataval[2].trim(),
							dataval2[0].trim(), Float.parseFloat(confidence),
							RdbIndexType.ALL);
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}

			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("Querying System");
		// querySystem("Jorunn_Danielsen", "phone", "tel22198709", new
		// Float(0.8),
		// RdbIndexType.SPO, 12);
		I3.querySystem("dexxter", null, null, null, RdbIndexType.SC, 5);
		I3.querySystem(null, "name", null, null, RdbIndexType.PSO, 15);
		System.out.println("Querying done");
		PCounter.getStatistics();
	}
}
